<template>
  <div>
    <a-modal :title="'作品添加'" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel1">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="选择系列">
          <a-select show-search :default-active-first-option="false" :show-arrow="false" :filter-option="false"
            :not-found-content="null" @search="seriesSearch"
            :placeholder="form.seriesName ? form.seriesName : '请选择或输入关键字'" @change="selectSeries">
            <a-select-option :value="item._id" v-for="(item, index) in sList" :key="index">
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="集数" type="number" >
            <a-input v-model="form.episodes" type="number" 
                onmousewheel="return false" 
                onkeypress="return event.key >= '0' && event.key <= '9'"/>
        </a-form-model-item>
        <!-- <a-form-model-item label="价格">
          <a-input v-model="form.price" :disabled="editPrice" />
        </a-form-model-item> -->
        <a-form-model-item label="*价格（元）">
          <a-select v-model="form.price" :disabled="editPrice" >
              <a-select-option value="1">1</a-select-option>
              <a-select-option value="0.88">0.88</a-select-option>
              <a-select-option value="0.8">0.8</a-select-option>
              <a-select-option value="0.66">0.66</a-select-option>
              <a-select-option value="0.6">0.6</a-select-option>
              <a-select-option value="0.55">0.55</a-select-option>
              <a-select-option value="0.5">0.5</a-select-option>
              <a-select-option value="0.45">0.45</a-select-option>
              <a-select-option value="0.4">0.4</a-select-option>
              <a-select-option value="0.3">0.3</a-select-option>
              <a-select-option value="0.2">0.2</a-select-option>
              <a-select-option value="0.1">0.1</a-select-option>
              <a-select-option value="0">0</a-select-option>
          </a-select>     
        </a-form-model-item>
        <a-form-model-item label="描述">
          <a-input v-model="form.detail" />
        </a-form-model-item>
        <a-form-model-item label="抖音变现">

          <a-radio-group v-model:value="form.realization">
            <a-radio value="adControl">单广告</a-radio>
            <a-radio value="priceControl">单付费</a-radio>
            <a-radio value="priceAdControl">广告+付费</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="快手变现">
          <a-radio-group v-model:value="form.realizationKs">
            <a-radio :disabled="true" value="adControlKs">单广告</a-radio>
            <a-radio value="priceControlKs">单付费</a-radio>
            <a-radio :disabled="true" value="priceAdControlKs">广告+付费</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="视频">

          <a-upload :remove="handleRemove" :before-upload="beforeUpload" :file-list="fileList">
            <a-button>
              上传
            </a-button>
          </a-upload>
          <a-progress v-if="fileList.length > 0" :percent="percent" type="line" />


        </a-form-model-item>

        <a-spin tip="视频上传中..." :spinning="spinning">
          <a-alert message=""></a-alert>
        </a-spin>
      </a-form-model>
    </a-modal>

  </div>
</template>

<script>

import axios from 'axios'
import { getSeriesList, addVideoList, modifyVideo, } from "../../http/api"
import { number } from 'echarts'
import loading from "../../components/loading.vue"
export default {
  name: "userEdit",
  data () {
    return {
      visible: this.flag,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      typeOptions: [],
      load: 1,
      spinning: false,
      form: {
        _id: '',
        videoUrl: '',
        FileId: '',
        episodes: '',
        seriesId: '',
        seriesName: '',
        detail: '',
        realization: '',
        realizationKs: '',
        price: '0.88',
        realization: 'priceControl',
        realizationKs: 'priceControlKs',
      },
      shopType: '',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      imgData: {},
      editPrice: false,//是否可以修改价格


      editType: 1, //1是新增 2是编辑

      bList: [],
      sList: [],
      gList: [],
      userInfo: {},

      percent: 0,//视频上传进度,
      FileId: ''
    }
  },
  props: ["flag", "list"],
  created () {
   
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (this.list._id) {
      let realization = ''
      let realizationKs = ''
      if (this.list.adControl == 'true') {
        realization = 'adControl'
      }
      if (this.list.priceControl == 'true') {
        realization = 'priceControl'
      }
      if (this.list.priceAdControl == 'true') {
        realization = 'priceAdControl'
      }
      if (this.list.adControlKs == 'true') {
        realizationKs = 'adControlKs'
      }
      if (this.list.priceControlKs == 'true') {
        realizationKs = 'priceControlKs'
      }
      if (this.list.priceAdControlKs == 'true') {
        realizationKs = 'priceAdControlKs'
      }
      console.log(this.list.price)


      this.form = {
        _id: this.list._id,
        videoUrl: this.list.videoUrl,
        FileId: this.list.FileId ? this.list.FileId : '',
        episodes: this.list.chapter,
        // episodesType: this.list.chapterType ? this.list.chapterType : '0',
        seriesId: this.list.seriesId,
        detail: this.list.detail,
        seriesName: this.list.seriesName,
        realization: realization,
        realizationKs: realizationKs,
        price: this.list.price
      }
      console.log(this.form)
      this.editPrice = true
      this.editType = 2
      this.fileList = [{
        uid: -1,
        name: this.list.videoUrl,
        status: 'done',
        url: this.list.videoUrl,
      }]
    } else {
      this.editType = 1
    }
    this.imgData.token = this.list.imgToken
    this.shopType = this.$store.state.user.shopId
    // if (this.shopType == '000') {
    //   this.bossList(1, this.$store.state.user.shopId)
    // }
    this.getSeriesList()
  },
  methods: {
    handleChange (info) {
      let fileList = [...info.fileList]

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-2)

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url
        }
        return file
      })

      this.fileList = fileList
    },

    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      this.UploadVideo()
      return false
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },

    //上传视频
    async UploadVideo () {
      let that = this
      this.spinning = true
      const tcVod = new TcVod.default({
        getSignature: await that.getSignature() // 前文中所述的获取上传签名的函数
      })

      const uploader = tcVod.upload({
        mediaFile: that.fileList[0], // 媒体文件（视频或音频或图片），类型为 File
      })
      uploader.on('media_progress', function (info) {
        console.log(info.percent) // 进度
        that.percent = Number((Number(info.percent) * 100).toFixed(0))
        console.log(that.percent)
      })
      uploader.done().then(function (doneResult) {
        console.log('视频上传完成=====')
        console.log(doneResult)
        that.spinning = false
        that.videoUrl = doneResult.video.url
        that.FileId = doneResult.fileId

      })
    },



    //系列选择
    selectSeries (e) {
      console.log(e)
      //根据_id查找系列名seriesName
      // 使用 find 方法查询
      const item = this.sList.find(item => item._id === e)
      this.form.seriesId = e
      this.form.seriesName = item.title
    },
    //系列搜索
    seriesSearch (e) {
      console.log(e)

      this.getSeriesList(e)
    },
    //商品图片
    imgCancel () {
      this.previewVisible = false
    },

    //预览视频
    previewFile (file) {
      console.log('Your upload file:', file)

    },
    getSignature () {
      let url = 'https://text-2g54vgfvcc0aee2b-1327065262.ap-shanghai.app.tcloudbase.com/TcbRouterAu'
      return function () {
        return axios.post(url, {
          "$url": "getYunToken",
        }).then(function (response) {
          console.log(response)
          return response.data.signature // 确保返回的是签名值
        })
      }
    },

    //确认
    async handleOk (e) {
      console.log(this.fileList)
      // deal with doneResult
      // if (this.fileList.length == 0 || this.form.seriesName == '' || this.form.detail == '' || this.form.episodes == '' || this.form.seriesId == '') {
      //   this.$tishi("warning", '请完善信息')
      //   return
      // }

      if (this.form.seriesName == ''  || this.form.seriesId == '') {
        this.$tishi("warning", '系列不能为空')
        return
      }

      if (this.form.episodes == '') {
        this.$tishi("warning", '集数不能为空')
        return
      }

      if (this.form.detail == '') {
        this.$tishi("warning", '描述不能为空')
        return
      }

      if (this.fileList.length == 0) {
        this.$tishi("warning", '视频不能为空')
        return
      }

      let that = this
      that.confirmLoading = true
      // console.log(that.form)
      if (that.editType == 2) {
        //修改数据
        that.modifyVideo()
      } else {
        //新增数据
        that.addVideoList()
      }


    },
    //点击取消 关闭弹框赋值
    handleCancel1 (e) {
      console.log("Clicked cancel button")
      this.visible = false
      this.$emit("func", this.visible)
    },
    //点击确定 关闭弹框赋值
    closefz () {
      this.visible = false
      this.confirmLoading = false
      this.$emit("func", this.visible)
    },
    async addVideoList () {

      let adControl = ''
      let priceControl = ''
      let priceAdControl = ''
      if (this.form.realization == 'adControl') {
        adControl = 'true'
        priceControl = 'false'
        priceAdControl = 'false'
      }
      if (this.form.realization == 'priceControl') {
        adControl = 'false'
        priceControl = 'true'
        priceAdControl = 'false'
      }
      if (this.form.realization == 'priceAdControl') {
        adControl = 'false'
        priceControl = 'false'
        priceAdControl = 'true'
      }
      let adControlKs = ''
      let priceControlKs = ''
      let priceAdControlKs = ''
      if (this.form.realizationKs == 'adControlKs') {
        adControlKs = 'true'
        priceControlKs = 'false'
        priceAdControlKs = 'false'
      }
      if (this.form.realizationKs == 'priceControlKs') {
        adControlKs = 'false'
        priceControlKs = 'true'
        priceAdControlKs = 'false'
      }
      if (this.form.realizationKs == 'priceAdControlKs') {
        adControlKs = 'false'
        priceControlKs = 'false'
        priceAdControlKs = 'true'
      }
      const parameter = {
        "$url": "addVideoList",
        "videoUrl": this.videoUrl,
        "seriesID": this.form.seriesId,
        "seriesName": this.form.seriesName,
        "chapter": Number(this.form.episodes),
        // "chapterType": this.form.episodesType,
        "author": this.userInfo.name,
        "authorID": this.userInfo._id,
        "detail": this.form.detail,
        "FileId": this.FileId,
        adControl,
        price: this.form.price,
        priceControl,
        priceAdControl,
        adControlKs,
        priceControlKs,
        priceAdControlKs,

      }
      var res = await addVideoList(parameter)
      console.log('新增视频数据', res)
      if (res.code == 200) {
        this.$tishi("success", res.msg)
        this.closefz()
      } else {
        this.$tishi("warning", res.msg)
        this.confirmLoading = false
      }
    },
    //视频数据修改
    async modifyVideo () {
      console.log(this.fileList)
      //判断是否修改了视频
      let videoUrl = ''
      let FileId = ''
      if (this.fileList[0].url) {
        videoUrl = this.fileList[0].url
        FileId = this.form.FileId
      } else {
        videoUrl = this.videoUrl
        FileId = this.FileId
      }
      let adControl = ''
      let priceControl = ''
      let priceAdControl = ''
      if (this.form.realization == 'adControl') {
        adControl = 'true'
        priceControl = 'false'
        priceAdControl = 'false'
      }
      if (this.form.realization == 'priceControl') {
        adControl = 'false'
        priceControl = 'true'
        priceAdControl = 'false'
      }
      if (this.form.realization == 'priceAdControl') {
        adControl = 'false'
        priceControl = 'false'
        priceAdControl = 'true'
      }
      let adControlKs = ''
      let priceControlKs = ''
      let priceAdControlKs = ''
      if (this.form.realizationKs == 'adControlKs') {
        adControlKs = 'true'
        priceControlKs = 'false'
        priceAdControlKs = 'false'
      }
      if (this.form.realizationKs == 'priceControlKs') {
        adControlKs = 'false'
        priceControlKs = 'true'
        priceAdControlKs = 'false'
      }
      if (this.form.realization == 'priceAdControlKs') {
        adControlKs = 'false'
        priceControlKs = 'false'
        priceAdControlKs = 'true'
      }
      const parameter = {
        "$url": "modifyVideo",
        "seriesID": this.form.seriesId,
        "seriesName": this.form.seriesName,
        "chapter": Number(this.form.episodes),
        "detail": this.form.detail,
        "videoUrl": videoUrl,
        "_id": this.form._id,
        "FileId": FileId,
        adControl,
        priceControl,
        priceAdControl,
        adControlKs,
        priceControlKs,
        priceAdControlKs,
      }
      var res = await modifyVideo(parameter)
      console.log('修改系列', res)
      if (res.code == 200) {
        this.$tishi("success", res.msg)
        this.closefz()

      } else {
        this.$tishi("warning", res.msg)
        this.confirmLoading = false
      }
    },

    //系列列表
    async getSeriesList (keyword) {
      const parameter = {
        "$url": "getSeriesSearch",
        "keyword": keyword,
        "authorID": this.userInfo._id,
      }
      const res = await getSeriesList(parameter)
      console.log('系列列表', res)
      var d = res.res
      this.sList = d.data
    },
  },
  components: {
    loading,
  },
}
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>